#include <iostream>
#include "sk_storage/sk_storage.hpp"


namespace sk_storage {

void Sk::Init(const std::string &log_file) {
  reader_ = new log::Reader(log_file);
  mp_ = new MemMap();
  std::string log_info;
  while (reader_->Read(log_info) != -1) {
    log::DiskItem disk_item;
    disk_item.UnSerializeTo(log_info);
    mp_->Set(disk_item.log_id(), disk_item.key(), disk_item.value());
    log_info.clear();
  }
  delete reader_;
  writer_ = new log::Writer(log_file);
}

Status Sk::Set(const std::string &key, const std::string &value) {
  mu_.lock();
  if (mp_->IsImmutable()) {
    return SET_ERR;
  }
  log::DiskItem disk_item(key, value);
  std::string log_info;
  disk_item.SerializeTo(log_info);
  int lenstr = writer_->Write(log_info);
  Status status = SET_ERR; 
  if (lenstr == log_info.size() + 1) {
    status = mp_->Set(disk_item.log_id(), key, value);
  }
  mu_.unlock();
  return status;
}

Status Sk::Get(const std::string &key, std::string &value) {
  mu_.lock();
  Status status = mp_->Get(key, value);
  mu_.unlock();
  return status;
}

Sk::~Sk() {
  if (mp_ != nullptr) {
    delete mp_;
  }
}

} // namespace sk_storage
